package io.jee.caisan.weixin.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import io.jee.alaska.util.Result;
import io.jee.caisan.weixin.domain.SysConfig;
import io.jee.caisan.weixin.repository.SysConfigRepository;
import io.jee.caisan.weixin.service.SysConfigService;

@Service
@Transactional
public class SysConfigServiceImpl implements SysConfigService{
	
	@Resource
	private SysConfigRepository sysConfigRepository;

	@Override
	public Page<SysConfig> findPage(String type, Pageable pageable) {
		return sysConfigRepository.findAll(new Specification<SysConfig>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<SysConfig> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Set<Predicate> predicates = new HashSet<>();
                if(StringUtils.hasText(type)){
                    predicates.add(cb.equal(root.get("type"), type));
                }
                Predicate[] restrictions = new Predicate[predicates.size()];
                return query.where(predicates.toArray(restrictions)).getRestriction();
			}
		}, pageable);
	}

	@Override
	public Result<SysConfig> add(SysConfig sysConfig) {
		sysConfig.setEnable(true);
		sysConfigRepository.save(sysConfig);
		return Result.success(sysConfig);
	}

	@Override
	public Result<SysConfig> update(SysConfig sysConfig) {
		SysConfig entity = sysConfigRepository.findById(sysConfig.getId()).orElse(null);
		BeanUtils.copyProperties(sysConfig, entity, new String[] {"id", "enable"});
		sysConfigRepository.save(entity);
		return Result.success(entity);
	}

	@Override
	public Result<Void> delete(Integer[] ids) {
		sysConfigRepository.deleteBatch(Arrays.asList(ids));
		return Result.success();
	}

	@Override
	public Result<Integer> updateEnable(Integer id, boolean enable) {
		sysConfigRepository.update().set("enable", enable).where("id", id).end();
		return Result.success(id);
	}

	@Override
	public SysConfig findOneByType(Integer type) {
		List<SysConfig> list = sysConfigRepository.select().where("type", type).and("enable", true).order().asc("sort").asc("id").end().list();
		if(!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

}
